<template>
	<rui-pages>
		<view class="product">
			<image :src="info.image" mode="" class="product_image"></image>
			<view class="product_btn" @click="toControl">
				<rui-icons icon="setting" size="50"></rui-icons>
				<view class="product_btn_dot" v-if="product.getUpdate"></view>
			</view>
		</view>

		<view class="info">
			<view class="info_item">
				<view class="info_item_label">
					蓝牙连接
				</view>
				<view class="info_item_value" :style="`color:${info.color}`">
					{{info.connect ? '已连接':'未连接'}}
				</view>
			</view>
			<view class="info_item">
				<view class="info_item_label">
					水杯电量
				</view>
				<view class="info_item_value" :style="`color:${info.color}`">
					{{info.quantity}}%
					<!-- <view style="padding-top: 8rpx;">
						<rui-electricity :progress="info.quantity" :color="info.color"></rui-electricity>
					</view> -->
				</view>
			</view>
			<view class="info_item">
				<view class="info_item_label">
					喝水次数
				</view>
				<view class="info_item_value" :style="`color:${info.color}`">
					{{info.drink}}次
				</view>
			</view>
			<view class="info_item">
				<view class="info_item_label">
					录入指纹
				</view>
				<view class="info_item_value" :style="`color:${info.color}`">
					{{product.getFingerprint}}枚
				</view>
			</view>
		</view>
		<view class="btn-box">
			<view class="btn-box_item" @click="openCup">
				蓝牙解锁
			</view>
			<view class="btn-box_item"
				@click="$rui.route('/pages/product/cup-c1/enter/enter', {user_product_id: info.user_product_id})">
				添加指纹
			</view>
		</view>


		<rui-title title="今日喝水"></rui-title>
		<rui-card>
			<view class="drink">
				<view class="charts">
					<rui-charts-wave :color="info.color" :progress="info.progress" size="300rpx"></rui-charts-wave>
				</view>
				<view class="drink_info">
					<view class="drink_info_number" :style="`color:${info.color}`">
						{{info.drink}}次
					</view>
					<view class="drink_info_desc">
						默认开盖1次喝水35ml；
					</view>
				</view>
			</view>
			<view class="drink_tips">
				{{tips}}
			</view>
		</rui-card>
		<!-- <rui-popup ref="popup">
			<view class="drink_tips">
				<view class="drink_info_item">
					9岁-13岁：男孩1500-1800ml(最低开盖43次); 女孩1200-1600ml(最低开盖34次)；
				</view>
				<view class="drink_info_item">
					13岁-18岁：男孩2000-2500ml(最低开盖57次); 女孩1500-1700ml(最低开盖43次)；
				</view>
			</view>
		</rui-popup> -->

		<rui-title title="喝水记录"></rui-title>
		<rui-date :color="info.color" @change="changeDate"></rui-date>
		<rui-card>
			<view class="record">
				<view class="record_info">
					<view class="record_info_head">
						<view class="record_info_head_number" :style="`color:${info.color}`">{{drink_number}}</view>
						<view class="record_info_head_name">
							当日喝水
						</view>
					</view>
					<view class="record_info_body">
						<view class="record_info_body_item" v-for="(item,index) in lock_list" :key="index">
							<view class="record_info_body_item_time">
								{{item.log_at}}
							</view>
							<view class="record_info_body_item_content">
								{{item.content}}
							</view>
						</view>
					</view>
				</view>
			</view>
		</rui-card>

		<!-- <rui-title title="全年累计"></rui-title>
		<rui-card>
			<rui-charts-bar :color="info.color"></rui-charts-bar>
		</rui-card> -->
		<view class="version" v-if="info.version">
			v.1.0.{{info.version}}
		</view>

		<!-- 加载失败蒙层 -->
		<rui-loading ref="refLoading" :message="loading.message"></rui-loading>
		<!-- 	<view class="loading" v-if="loading.status">
			<view class="loading_body">
				<view class="loading_body_icon"></view>
				<view class="loading_body_name">
					{{loading.error ? '加载失败':'设备加载中'}}
				</view>
				<view class="loading_body_message" v-if="loading.error">
					即将返回首页
				</view>
				<view class="loading_body_message" v-else>
					{{loading.message}}
				</view>
			</view>
		</view> -->
	</rui-pages>

</template>

<script setup>
	import {
		ref
	} from "vue"

	import {
		onLoad,
		onShow,
		onHide,
		onUnload,

	} from "@dcloudio/uni-app"
	import {
		getCupInfo,
		setCupLog,
		getCupLog,
		upStatus,
		addFinger,
		getFingerAll,
	} from "@/common/api.js"

	import ble from "@/util/ble.js"
	import tools from "@/util/tools"
	import {
		productStore
	} from "@/store"

	import {
		_handleBuffer,
		_sum,
		_handleElectricity,
		_chunkArray,
		createBuffer
	} from "@/util/common.js"

	let product = productStore()
	let refLoading = ref();

	let info = ref({
		connect: false, //连接状态
		quantity: 0, //电量
		drink: 0, //喝水次数
		fingerprint: 0, //指纹数量
		color: "#67c8f2", //水杯颜色
		image: "", //产品图片
		progress: 0, //每日完成进度
		user_product_id: 0, //个人产品ID
		product_id: 0, //产品ID
		version: 0 //版本号
	})
	//喝水温馨提示
	let tips = ref("")

	//喝水次数
	let drink_number = ref(0)

	//水杯配置
	let config = {}

	//开锁记录列表
	let lock_list = ref([])

	let loading = ref({
		message: "请触摸指纹激活水杯",
		status: true,
		error: false,
		second: 5,
		// remainder: 30
	})
	let connect_status = ref(false);
	let isFirstLoad = true;


	onShow(() => {
		//检查蓝牙是否开启
		uni.getBluetoothAdapterState({
			success(res) {
				if (!res.available) {
					uni.showToast({
						title: "请开启蓝牙",
						icon: "error"
					})
				}
			}
		})

		console.log('show --------')
		onBle()
	})

	onHide(() => {
		console.log('hide --------')
		if (!isFirstLoad) {
			console.log('页面首次显示');
		}

		ble.watch = function() {}
		ble.error = function() {}

	})

	onUnload(() => {
		ble.close()
		ble.watch = function() {}
		ble.error = function() {}
	})

	onLoad(opts => {
		ble.debug()

		isFirstLoad = true;

		info.value.color = opts.color
		info.value.image = opts.image
		info.value.user_product_id = opts.id;
		info.value.product_id = opts.product_id;
		info.value.connect = false;

		console.log('opts', opts)

		//设置蓝牙设备ID
		ble.config({
			deviceId: opts.mac,
			serviceId: "6E400001-B5A3-F393-E0A9-E50E24DC4179",
			// key: "6E40"
			properties(type, uuid) {
				if (type == 'write') {
					return uuid.includes("6E400002")
				}
				if (type == 'notify') {
					return uuid.includes("6E400003")
				}
			}
		})

		//获取水杯配置
		getConfig(opts.id);
		//设置首页标题
		uni.setNavigationBarTitle({
			title: opts.name || "设备首页"
		});

		ble.error = (event, d) => {
			console.log(event, d)
			//设备连接失败
			// if (d.code == 10007 || event == "connection" || event === "services" || event ===
			// 	"characteristics") {
			// 	info.value.connect = false;
			// 	quit()
			// }
			if(event == 'quit') {
				info.value.connect = false;
				quit()
			}
		}
		const quit = (msg) => {
			refLoading.value.error(msg || "设备断开")
			loading.value.error = true;
			setTimeout(_ => {
				uni.navigateBack({
					delta: 1
				})
			}, 5000)
		}
	})

	const onBle = () => {
		ble.watch = (event, d) => {
			console.log(event, d)
			if (event == 'state2') {
				loading.value.message = `请触摸指纹激活水杯 ${d.remainder}s`
			}
			if (event === 'state') {
				info.value.connect = d.connected;
				if (d.connected) {
					loading.value.message = "数据加载中"
				} else {
					quit(d.msg)
				}
			}
			if (event == 'notify') {
				if (d.command == "40") {
					info.value.connect = true;
					//电量
					info.value.quantity = _handleElectricity(d.data[3] + d.data[4])

					console.log("电量十六进制：", d.data[3] + d.data[4], "电量百分比：", info.value.quantity)

					//开锁次数
					drink_number.value = info.value.drink = parseInt(d.data[5] + d.data[6], 16)
					//喝水进度
					let total = config.added[config.alias]
					info.value.progress = parseInt((drink_number.value / Number(total)).toFixed(2) * 100);
					//指纹数量
					// info.value.fingerprint = parseInt(d.data[2], 16)
					let finger_number = parseInt(d.data[2], 16);
					product.setFingerprint(finger_number)
					//同步指纹
					syncFinger(finger_number)
					//版本号
					info.value.version = parseInt(d.data[1], 16);
					ota(info.value.version)
					console.log('版本号', info.value.version)
					//关闭蒙层
					// loading.value.status = false;
					refLoading.value.close();
					//获取当日喝水记录
					ble.send(createBuffer(15))
				}

				if (d.command == "15") {
					let data = d.data.slice(1);
					data = _chunkArray(data, 5);
					console.log('开锁总记录', data)
					let list15 = [];
					for (let i = 0; i < data.length; i++) {
						let msg = ['密码开锁', '指纹解锁', '蓝牙解锁'][parseInt(data[i][4], 16)]
						data[i].pop()
						let stamp = data[i].join("")
						stamp = parseInt(stamp, 16)
						if (stamp > 1000000000) {
							list15.unshift({
								content: msg + "1次",
								log_at: tools.formatDate(stamp * 1000, 'Y/M/D h:m')
							})
						}
					}

					lock_list.value = list15.sort((a, b) => b.log_at.localeCompare(a.log_at));
					//加入心跳
					ble.ping(14);
					console.log("心跳开始")
					ble.send(createBuffer(19))
				}

				if (d.command == "19") {

					let data = d.data.slice(1).slice(0, -1);
					data = _chunkArray(data, 6);
					let list = [];
					for (let i = 0; i < data.length; i++) {
						let numbers = parseInt([...data[i]].slice(4).join(""), 16);
						let stamp = parseInt([...data[i]].splice(0, 4).join(""), 16)
						let now_stamp = new Date().getTime();
						if (stamp > 1000000000 && stamp < now_stamp) {
							list.push({
								numbers,
								log_at: tools.formatDate(stamp * 1000, 'Y/M/D h:m')
							})
							console.log('----开锁总记录', numbers, tools.formatDate(stamp * 1000, 'Y/M/D h:m'))
							//同步每日开锁数据
							setCupLog({
								user_product_id: info.value.user_product_id,
								log_at: tools.formatDate(stamp * 1000, 'Y-M-D'),
								category: 1,
								numbers
							})
						}
					}
				}
			}

			if (event === 'start') {
				let data = (new Date().getTime() / 1000 >> 0).toString(16);
				ble.send(createBuffer(40, 4, data), '', 500)
			}
		}
	}
	/**
	 * 同步指纹
	 */
	const syncFinger = (number) => {
		getFingerAll({
			user_product_id: info.value.user_product_id
		}).then(res => {
			/**
			 * 判断数据库指纹数量与设备数量是否相符
			 * 1、设备指纹数量未同步至数据库
			 * 2、查找缺失的key
			 * 3、提交设备录入的key
			 */
			let keys = res.data.keys;
			if (res.data.number >= 10) return;
			if (number > res.data.number) {
				let k = [];
				for (let key = 0; key <= number; key++) {
					if (!keys.includes(key) && key > 0) {
						//同步设备录入指纹
						console.log('------------未同步指纹', key)
						k.push(key)
					}
				}
				if (!k.length) return false;

				addFinger({
					name: "设备指纹",
					user_product_id: info.value.user_product_id,
					keys: k.join(',')
				}).then(res => {
					console.log(2222222)
				})
			}
		})
	}

	const toControl = () => {
		uni.navigateTo({
			url: "/pages/product/cup-c1/control/control",
			success() {
				ble.show()
			}
		})
	}


	const ota = (ver) => {
		product.setVersion(ver)
		product.setUpdate(false)
		// 对比版本是否升级。
		if (config.version.v > ver) {
			product.setUpdate(true)
			if (config.version.grade == 0) {
				_toOta()
			} else if (config.version.grade == 1) {
				setTimeout(_ => {
					uni.showModal({
						title: "升级提示",
						content: "发现新版本是否升级？",
						success(res) {
							if (res.confirm) _toOta()
						}
					})
				}, 1000)
			}
		}

		function _toOta() {
			uni.redirectTo({
				url: "/pages/product/cup-c1/ota/ota"
			});
		}
	}

	/**   
	 * 获取水杯配置
	 * @param {number} id 
	 */
	const getConfig = (id) => {
		getCupInfo({
			id
		}).then(res => {
			config = res.data;
			product.setInfo(res.data);
			ble.connect();
			console.log('config', config)
			tips.value = {
				girl: '温馨提示：9岁-18岁女孩建议喝水1200-1800ml，需开盖34-43次即可达标。',
				boy: '温馨提示：13岁-18岁男孩2000-2500ml, 需开盖50-57次即可达标。'
			} [config.alias];
		})
	}

	//获取指定时间喝水次数
	const changeDate = date => {
		if (isNowDate(date)) {
			drink_number.value = info.value.drink;
			return;
		}
		getCupLog({
			user_product_id: info.value.user_product_id,
			date
		}).then(res => {
			drink_number.value = res.data.number || 0;
		})
	}
	const isNowDate = (date) => {
		const now = new Date();
		now.setHours(0, 0, 0, 0);
		const now2 = new Date(date);
		now2.setHours(0, 0, 0, 0);
		return now2.getTime() == now.getTime();
	}

	//蓝牙解锁水杯
	const openCup = () => {
		uni.showLoading({
			title: '开锁中',
			mask: true,
		});
		setTimeout(() => {
			uni.hideLoading();
		}, 1000)
		ble.send(createBuffer(10), () => {
			info.value.drink++
			drink_number.value++
			lock_list.value.unshift({
				content: "蓝牙解锁1次",
				log_at: tools.formatDate(new Date().getTime(), 'Y/M/D h:m')
			})

		})
	}
</script>

<style lang="scss" scoped>
	.btn-box {
		display: flex;

		&_item {
			background: #fff;
			padding: 30rpx;
			margin: 20rpx;
			border-radius: 20rpx;
			width: calc(50% - 100rpx);
			text-align: center;
		}
	}

	.loading {
		backdrop-filter: blur(20rpx);
		position: fixed;
		top: 0;
		width: 100%;
		height: 100%;
		z-index: 100;

		&_body {
			margin-top: 50%;
			text-align: center;



			&_icon {
				border-radius: 50%;
				width: 100rpx;
				height: 100rpx;
				margin: 20rpx auto 100rpx;
				position: relative;
			}

			&_name {
				font-size: 36rpx;
				font-weight: bold;
			}

			&_message {
				font-size: 28rpx;
				color: #999;
				margin-top: 10rpx;
			}

			&_error {
				font-size: 28rpx;
				color: #aaa;
				margin-top: 20rpx;
			}
		}

		.loading_body_icon:before,
		.loading_body_icon:after {
			content: "";
			position: absolute;
			top: 0;
			color: var(--color);
			background-color: currentColor;
			width: 100%;
			height: 100%;
			display: block;
			border-radius: 50%;
			transition: all 1s;
			-webkit-animation: pulse 3s ease-out infinite;
			animation: pulse 3s ease-out infinite;
		}

		.loading_body_icon:after {
			-webkit-animation-delay: 0.4s;
			animation-delay: 0.4s;
			-webkit-animation-timing-function: cubic-bezier(0.3, 1.65, 0.7, -0.65);
			animation-timing-function: cubic-bezier(0.3, 1.65, 0.7, -0.65);
		}

		@keyframes pulse {
			0% {
				transform: scale(0);
				color: var(--color);
			}

			75%,
			100% {
				transform: scale(3);
				color: transparent;
			}
		}

		@keyframes pulseColor {

			50%,
			90% {
				color: var(--color);
			}

			70% {
				color: var(--color);
			}
		}
	}

	.version {
		text-align: center;
		padding: 15rpx 0;
		color: #ddd;
	}

	.drink {
		display: flex;
		justify-content: space-between;
		align-items: center;
		--w: 320rpx;

		&_charts {
			width: var(--w);
		}

		&_tips {
			margin-top: 50rpx;
			font-size: 28rpx;
			color: #999;
			// white-space: nowrap;
			// overflow: hidden;
			// text-overflow: ellipsis;
		}

		&_info {
			&_desc {
				font-size: 28rpx;
			}

			&_number {
				font-size: 44rpx;

				&::before {
					content: "今日喝水";
					font-size: 28rpx;
				}
			}


		}
	}

	.btn {
		background: #fff;
		padding: 30rpx;
		margin: 20rpx;
		border-radius: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.record {
		&_info {
			display: flex;
			--w: 160rpx;

			&_body {
				width: calc(100% - var(--w));

				&_item {
					display: flex;
					margin: 10rpx 0;
					font-size: 28rpx;
					color: #999;

					&_content {
						margin-left: 10rpx;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
					}
				}
			}

			&_head {
				width: var(--w);

				&_name {
					font-size: 28rpx;
				}

				&_number {
					font-size: 60rpx;
					font-weight: bold;

					&::after {
						content: "次";
						font-size: 28rpx;
					}
				}
			}
		}

	}

	.info {
		display: flex;
		justify-content: space-between;
		background: #fff;
		padding: 30rpx;
		margin: 20rpx;
		border-radius: 20rpx;

		&_item {
			width: 25%;
			text-align: center;

			&_label {
				margin-bottom: 20rpx;
				font-size: 28rpx;
			}

			&_value {
				font-weight: bold;
			}
		}
	}

	.product {
		position: relative;
		padding: 30rpx;
		text-align: center;



		&_btn {
			position: absolute;
			top: 0;
			right: 0;
			width: 100rpx;
			height: 100rpx;
			text-align: center;
			line-height: 100rpx;

			&_dot {
				position: absolute;
				top: 10rpx;
				right: 20rpx;
				width: 20rpx;
				height: 20rpx;
				border-radius: 50%;
				background: #f00;
			}
		}

		&_image {
			width: 300rpx;
			height: 300rpx;
		}
	}
</style>